#include "logindialog.h"
#include "ui_logindialog.h"
#include<QPushButton>
#include<QDebug>
#include"httpmgr.h"
#include"tcpmgr.h"
LoginDialog::LoginDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::LoginDialog)
{
    ui->setupUi(this);

    connect(ui->register_btn,&QPushButton::clicked,this,&LoginDialog::switchRegister);
    ui->forget_label->SetState("normal","hover","","selected","selected_hover","");
    ui->forget_label->setCursor(Qt::PointingHandCursor);
    connect(ui->forget_label,&ClickedLabel::clicked,this,&LoginDialog::slot_forget_pwd);

    ui->forget_label->SetState("unvisible","unvisible_hover","","visible","visible_hover","");

    connect(HttpMgr::GetInstance().get(),&HttpMgr::sig_login_mod_finish,this,&LoginDialog::slot_login_mod_finish);

    connect(ui->email_lineEdit,&QLineEdit::editingFinished,this,&LoginDialog::checkEmailVaild);
    connect(ui->pwd_lineEdit,&QLineEdit::editingFinished,this,&LoginDialog::checkPassVaild);

    initHttpHandlers();

    ui->pass_visible->setCursor(Qt::PointingHandCursor);
    ui->pass_visible->SetState("unvisible","unvisible_hover","","visible","visible_hover","");
    ui->pwd_lineEdit->setEchoMode(QLineEdit::Password);
    connect(ui->pass_visible,&ClickedLabel::clicked,this,[this](){
        auto state =ui->pass_visible->GetCurState();
        if(state==ClickLbState::Normal){
            ui->pwd_lineEdit->setEchoMode(QLineEdit::Password);
        }
        else{
            ui->pwd_lineEdit->setEchoMode(QLineEdit::Normal);
        }
        qDebug() << "Label was clicked!";
    });
    //发出连接请求
    connect(this,&LoginDialog::sig_connect_tcp,TcpMgr::GetInstance().get(),&TcpMgr::slot_tcp_connect);
    //连接管理发出连接成功
    connect(TcpMgr::GetInstance().get(),&TcpMgr::sig_con_success,this,&LoginDialog::slot_con_finish);

}

LoginDialog::~LoginDialog()
{
    delete ui;
}

bool LoginDialog::checkEmailVaild()
{
    auto email=ui->email_lineEdit->text();
    QRegularExpression regex(R"((\w+)(\.|_)?(\w*)@(\w+)(\.(\w+))+)");
    bool match=regex.match(email).hasMatch();
    if(!match){
        AddTipErr(TipErr::TIP_EMAIL_ERR,tr("邮箱不正确"));
        return false;
    }

    DelTipErr(TipErr::TIP_EMAIL_ERR);
    return true;
}

bool LoginDialog::checkPassVaild()
{
    auto pass=ui->pwd_lineEdit->text();
    if(pass.length()<6||pass.length()>15){
        AddTipErr(TipErr::TIP_PWD_ERR,tr("密码长度应为6~15"));
        return false;
    }
    //正则表达式设置密码
    QRegularExpression regExp("[a-zA-Z0-9!@#$%^&*.]{6,15}$");
    bool match =regExp.match(pass).hasMatch();
    if(!match){
        AddTipErr(TipErr::TIP_PWD_ERR,tr("不能包含非法字符"));
        return false;
    }
    DelTipErr(TipErr::TIP_PWD_ERR);
    return true;
}

void LoginDialog::AddTipErr(TipErr te, QString tips)
{
    _tip_errs[te]=tips;
    showTip(tips,false);
}

void LoginDialog::DelTipErr(TipErr te)
{
    _tip_errs.remove(te);
    if(_tip_errs.empty()){
        ui->error_label->clear();
        return;
    }
    showTip(_tip_errs.first(),false);
}

void LoginDialog::showTip(QString str, bool b_ok)
{
    if(b_ok){
        ui->error_label->setProperty("state","normal");
    }
    else{
        ui->error_label->setProperty("state","err");
    }
    ui->error_label->setText(str);
    repolish(ui->error_label);
}

void LoginDialog::initHttpHandlers()
{
    _handlers.insert(ReqId::ID_LOGIN_USER,[this](QJsonObject json_obj){
        int error=json_obj["error"].toInt();
        if(error!=ErrorCodes::SUCCESS){
            showTip(tr("调用参数错误"),false);

            return;
        }
        showTip(tr("登陆成功"),true);
        ServerInfo server;
        server.Host=json_obj["host"].toString();
        server.Uid=json_obj["uid"].toInt();
        server.Port=json_obj["port"].toString();
        server.Token=json_obj["token"].toString();


        _uid=server.Uid;
        _token=server.Token;
        auto email=json_obj["email"].toString();
        qDebug()<<"email is: "<<email<<",host is: "<<server.Host<<",port is: "<<server.Port;

        emit sig_connect_tcp(server);
        return;
    });
}

void LoginDialog::slot_forget_pwd()
{
    qDebug()<<"slot forget pwd";
    emit switchReset();
}

void LoginDialog::on_login_btn_clicked()
{
    qDebug()<<"login btn click";
    if(checkEmailVaild()==false){

        return;
    }
    if(checkPassVaild()==false){
        return;
    }

    auto email=ui->email_lineEdit->text();
    auto pwd=ui->pwd_lineEdit->text();
    QJsonObject json_obj;
    json_obj["email"]=email;
    json_obj["passwd"]=xorString(pwd);
    HttpMgr::GetInstance()->PostHttpReq(QUrl(gate_url_prefix+"/user_login"),
                                        json_obj,ReqId::ID_LOGIN_USER,Modules::LOGINMOD);
}

void LoginDialog::slot_login_mod_finish(ReqId id, QString res, ErrorCodes err)
{
    if(err!=ErrorCodes::SUCCESS){
        showTip(tr("网络请求错误"),false);
        return;
    }
    QJsonDocument json_doc=QJsonDocument::fromJson(res.toUtf8());
    if(json_doc.isNull()){
        showTip(tr("json解析错误"),false);
        return;
    }
    if(!json_doc.isObject()){
        showTip(tr("json解析错误"),false);
        return;
    }

    _handlers[id](json_doc.object());
    return;

}

void LoginDialog::slot_con_finish(bool bsuccess)
{
    if(bsuccess){
        showTip(tr("聊天服务连接成功，正在登录......"),true);
        QJsonObject jsonObj;
        jsonObj["uid"]=_uid;
        jsonObj["token"]=_token;

        QJsonDocument doc(jsonObj);
        QByteArray jsonString=doc.toJson(QJsonDocument::Indented);
        emit TcpMgr::GetInstance()->sig_send_data(ReqId::ID_CHAT_LOGIN,jsonString);

    }
    else{
        showTip(tr("网络异常"),false);

    }
}

void LoginDialog::slot_login_failed(int err)
{
    QString result=QString("登录失败，err is %1").arg(err);
    showTip(result,false);

}

